package com.example.tally;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.tally.adapter.AccountAdapter;
import com.example.tally.db.AccountBean;
import com.example.tally.db.DBManager;
import com.example.tally.utils.CalendarDialog;
import com.joybar.librarycalendar.data.CalendarDate;
import com.joybar.librarycalendar.fragment.CalendarViewFragment;
import com.joybar.librarycalendar.fragment.CalendarViewPagerFragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class HistoryActivity extends AppCompatActivity implements View.OnClickListener,
        CalendarViewPagerFragment.OnPageChangeListener,
        CalendarViewFragment.OnDateClickListener,
        CalendarViewFragment.OnDateCancelListener {
    ListView historyLv;
    TextView timeTv,sumTv;
    List<AccountBean> mData;
    AccountAdapter adapter;
    int year , month,day;

    /**记录点击之后年份和月份的位置，否则每次返回再打开的时候总是刚开始的位置*/
    int dialogSelectPos = -1;
    int dialogSelectMonth = -1;

    int MENU_UPDATE = 0;
    int MENU_DELETE = 1;

    private boolean isChoiceModelSingle = true;
    private List<CalendarDate> mListDate = new ArrayList<>();

    private CalendarViewPagerFragment fragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        historyLv = findViewById(R.id.history_lv);
        timeTv = findViewById(R.id.history_tv_time);
        sumTv = findViewById(R.id.history_tv_sum);
        initFragment();
        /**适配器前或者后，先尝试前面——>失败：闪退*/
        initTime();
//        loadData();
        timeTv.setText(year + "年" +month + "月");
        mData = new ArrayList<>();
        // 设置适配器
        adapter = new AccountAdapter(this , mData);
        historyLv.setAdapter(adapter);
        /**适配器前或者后，尝试后面——>成功*/
        //initTime();
        //loadData(year , month,day);
        registerForContextMenu(historyLv);
        //setListViewLongOnClickListener();
    }

    private void initFragment(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        // Fragment fragment = new CalendarViewPagerFragment();
        fragment = CalendarViewPagerFragment.newInstance(isChoiceModelSingle);
        tx.replace(R.id.fl_content, fragment);
        tx.commit();
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, MENU_UPDATE, 0, "修改记录");
        menu.add(0, MENU_DELETE, 0, "删除记录");
    }

    public boolean onContextItemSelected(MenuItem item) {
        //获取上下文菜单适配器
        AdapterView.AdapterContextMenuInfo cmi=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        //获取被选择的菜单位置
        int posMenu=cmi.position;
        //将菜单项与列表视图的条目相关联
        AccountBean bean=(AccountBean) adapter.getItem(posMenu);
        switch(item.getItemId()){
            case 0://执行该菜单条目的业务逻辑
                ArrayList<String> stringList = new ArrayList<String>();
                stringList.add(bean.getId()+"");
                stringList.add(bean.getTypeName()+"");
                stringList.add(bean.getsImageId()+"");
                stringList.add(bean.getBeizhu()==null?"":bean.getBeizhu());
                stringList.add(bean.getMoney()+"");
                stringList.add(bean.getTime()+"");
                stringList.add(bean.getYear()+"");
                stringList.add(bean.getMonth()+"");
                stringList.add(bean.getDay()+"");
                stringList.add(bean.getKind()+"");
                stringList.add("histroy");   //代表跳转方向
                Intent intent = new Intent();
                intent.setClass(this, RecordActivity.class);
                intent.putStringArrayListExtra("ListString", stringList);
                this.startActivity(intent);
                break;
            case 1:
                //执行该菜单条目的业务逻辑
                // 弹出提示用户是否删除的对话框
                delectItem(bean);
                break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onDateClick(CalendarDate calendarDate) {
        year = calendarDate.getSolar().solarYear;
        month = calendarDate.getSolar().solarMonth;
        day = calendarDate.getSolar().solarDay;
        timeTv.setText(year + "年" +month + "月"+day+"日");
        if(TextUtils.isEmpty(calendarDate.getOutcome())&&TextUtils.isEmpty(calendarDate.getIncome())){
            sumTv.setText("");
        }else {
            String outcomStr = calendarDate.getOutcome().replaceFirst("[-+]","");
            String incomStr = calendarDate.getIncome().replaceFirst("[-+]","");
            if(outcomStr.equals("")) {
                outcomStr = "0";
            }
            if(incomStr.equals("")) {
                incomStr = "0";
            }
            sumTv.setText("支出:"+outcomStr+" 收入:"+incomStr);
        }
        if (isChoiceModelSingle) {
            loadData(year,month,day);
        } else {
            //System.out.println(calendarDate.getSolar().solarDay);
            mListDate.add(calendarDate);
        }
    }

    @Override
    public void onDateCancel(CalendarDate calendarDate) {
        int count = mListDate.size();
        for (int i = 0; i < count; i++) {
            CalendarDate date = mListDate.get(i);
            if (date.getSolar().solarDay == calendarDate.getSolar().solarDay) {
                mListDate.remove(i);
                break;
            }
        }
    }

    @Override
    public void onPageChange(int year, int month) {
        timeTv.setText(year + "年" + month+"月");
        mListDate.clear();
        sumTv.setText("");
    }

    private static String listToString(List<CalendarDate> list) {
        StringBuffer stringBuffer = new StringBuffer();
        for (CalendarDate date : list) {
            stringBuffer.append(date.getSolar().solarYear + "-" + date.getSolar().solarMonth + "-" + date.getSolar().solarDay).append(" ");
        }
        return stringBuffer.toString();
    }

    private void delectItem(final AccountBean bean) {
        final int deleci_id = bean.getId();
        new AlertDialog.Builder(this).setTitle("提示信息")
                .setMessage("您确定要删除这个记录吗？")
                .setNegativeButton("取消" , null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DBManager.deleteItemFromAccounttbById(deleci_id);
                        mData.remove(bean);// 实时刷新，从数据源删除
                        adapter.notifyDataSetChanged();
                    }
                }).show();
    }

    private void loadData(int year , int month) {
        List<AccountBean> list = DBManager.getAccountListOneMonthFromAccounttb(year, month);
        mData.clear();
        mData.addAll(list);
        adapter.notifyDataSetChanged();
    }

    private void loadData(int year , int month,int day) {
        List<AccountBean> list = DBManager.getAccountListOneMonthFromAccounttb(year, month,day);
        mData.clear();
        mData.addAll(list);
        adapter.notifyDataSetChanged();
    }

    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 加载数据库数据的方法
        loadData(year , month,day);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.history_iv_back:
                finish();
                break;
            case R.id.history_iv_rili:
                CalendarDialog dialog = new CalendarDialog(this , dialogSelectPos , dialogSelectMonth);
                dialog.show();
                dialog.setDialogSize();
                dialog.setOnRefreshListener(new CalendarDialog.OnRefreshListener() {
                    @Override
                    public void Ensure(int selPos, int year, int month) {
                        timeTv.setText(year + "年" + month + "月");
                        //loadData(year , month);
                        dialogSelectPos = selPos;
                        dialogSelectMonth = month;
                        //这里需要重新换下日历了
                        //计算下相差几个月
                        fragment.setCurrentItem(year,month);
                        mData.clear();
                        adapter.notifyDataSetChanged();
                        historyLv.setAdapter(adapter);
                    }
                });
                break;
        }
    }
}